/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-03-25
*/
package com.rzico.basics.service;

import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.*;
import com.rzico.basics.mapper.PromotionMapper;
import com.rzico.basics.model.CouponMemberVo;
import com.rzico.exception.CustomException;
import com.rzico.basics.mapper.CouponCodeMapper;
import com.rzico.basics.mapper.CouponMapper;
import com.rzico.basics.model.CouponCodeVo;
import com.rzico.util.CodeGenerator;
import com.rzico.util.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <pre>
 * 我的卡券业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */

@Service
public class CouponCodeService extends BaseServiceImpl<CouponCode, String> {

    @Autowired
    private CouponCodeMapper couponCodeMapper;

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private CouponService couponService;

    @Autowired
    private MemberService memberService;

    @Override
    public BaseMapper<CouponCode, String> getMapper() {
        return couponCodeMapper;
    }

    public List<CouponCodeVo> selectVoList(Map<String, Object> params) {
        return couponCodeMapper.selectVoList(params);
    }

    /**
     * 发放卡券
     * @param list
     * @param enterprise
     * @param couponId
     * @param tagIds
     */
    @Transactional(rollbackFor = Exception.class)
    public void sendCoupon(List<CouponMemberVo> list, Enterprise enterprise, String sn, Long couponId, Long[] tagIds){
        Coupon coupon = couponService.selectByPrimaryKey(couponId);
        int code = 0;
        for (CouponMemberVo vo : list) {
            code ++;
            Member member = null;
            if (StringUtils.isNotEmpty(vo.getMobile())) {
                member = memberService.findByMobile(enterprise.getId(), vo.getMobile());
                if (member == null) {
                    //如果没自动添加注册会员
                    member = new Member();
                    member.setCreateDate(new Date());
                    member.setUsername("mch_" + enterprise.getMchId() + "_" + vo.getMobile());
                    member.setMchId(enterprise.getMchId());
                    member.setDeleted(false);
                    member.setMobile(vo.getMobile());
                    member.setPhone(vo.getMobile());
                    member.setName(vo.getName());
                    member.setVip(0);
                    member.setEnterpriseId(enterprise.getId());
                    member.setFreezePoint(0L);
                    member.setBalance(BigDecimal.ZERO);
                    member.setFreezeBalance(BigDecimal.ZERO);
                    member.setAmount(BigDecimal.ZERO);
                    member.setPoint(0L);
                    member.setAmount(BigDecimal.ZERO);
                    member.setMemberType(0);
                    member.setGender(2);
                    member.setTaxType(0);
                    member.setMatchPoint(0L);
                    member.setAchieve(BigDecimal.ZERO);
                    memberService.insertUseGeneratedKeys(member);
                }
                create(coupon, member.getId(), sn + code, vo.getNum());
            }
        }
    }

    /**
     * 发放卡券验证
     * @param list
     * @param couponId
     * @return
     */
    public Map<String, Object> sendCouponCheck(List<CouponMemberVo> list, Long couponId){
        Map<String,Object> result = new HashMap<>();
        result.put("returnCode","success");
        /*
         * 先用手机号查询member表,判断当前员工是否存在，
         * 再根据memberid与companyid查询companyemployee表判断员工是否在当前企业就职
         */
        int sendNum = 0;
        for (CouponMemberVo vo : list) {
            if (StringUtils.isEmpty(vo.getMobile())) {
                vo.setResult("手机号不能为空");
                result.put("returnCode", "error");
                break;
            }
            if (StringUtils.isEmpty(vo.getName())) {
                vo.setResult("姓名不能为空");
                result.put("returnCode", "error");
                break;
            }
            if (0 == vo.getNum()) {
                vo.setResult("发放数量不能为0");
                result.put("returnCode", "error");
                break;
            }
            sendNum += vo.getNum();
        }
        Coupon coupon = couponService.selectByPrimaryKey(couponId);
        if (0 > coupon.getStock().compareTo((long) sendNum)) {
            result.put("returnCode","error");
            result.put("returnMsg","发放数量大于卡券数量");
        }
        result.put("vo",list);
        return result;
    }

    public BigDecimal selectSumCount(Map<String, Object> params) {
        Map<String,BigDecimal> data = couponCodeMapper.selectSumCount(params);
        if (data !=null && data.containsKey("balance")) {
            return new BigDecimal(data.get("balance").toString());
        } else {
            return BigDecimal.ZERO;
        }

    }

    public BigDecimal selectVirtualCount(Map<String, Object> params) {
        Map<String,BigDecimal> data = couponCodeMapper.selectSumCount(params);
        if (data !=null && data.containsKey("stock")) {
            return new BigDecimal(data.get("stock").toString());
        } else {
            return BigDecimal.ZERO;
        }

    }



    @Transactional(rollbackFor = Exception.class)
    public void create(Coupon coupon, Long memberId, String sn, Integer quantity) {

        if (coupon.getType().equals(3) && (coupon.getMaxgiven()==null && coupon.getMaxgiven()==0)) {
           createAndInc(coupon,memberId,sn,quantity);
           return;
        }

        Date d = new Date();
            if (coupon.getBeginDate()!=null && coupon.getBeginDate().after(new Date())) {
                d = coupon.getBeginDate();
            }

            int w = 0;
            int s = 0;
            for (int i=0;i<quantity;i++) {

                w++;
                s++;

                CouponCode couponCode = new CouponCode();
                couponCode.setCreateDate(new Date());
                couponCode.setDeleted(false);
                couponCode.setCouponId(coupon.getId());
                couponCode.setBalance(1L);
                couponCode.setCreateDate(new Date());
                couponCode.setCode(sn+"-"+String.valueOf(s));
                couponCode.setEnterpriseId(coupon.getEnterpriseId());
                couponCode.setIsUsed(false);
                couponCode.setMemberId(memberId);
                couponCode.setStock(1L);

                if (coupon.getType().equals(3) && coupon.getMaxgiven()!=null && coupon.getMaxgiven()>0) {
                    d = DateUtils.truncate(d, Calendar.DATE);
                    if (w>coupon.getMaxgiven()) {
                        d = DateUtils.addMonths(d,1);
                        w = 0;
                    }
                    couponCode.setStartDate(d);
                    Date endDate = DateUtils.addSeconds(DateUtils.addMonths(d,1),-1);
                    couponCode.setVaildDate(endDate);
                } else {
                    couponCode.setStartDate(coupon.getBeginDate());
                    couponCode.setVaildDate(coupon.getEndDate());
                }

                super.insertUseGeneratedKeys(couponCode);

                Map<String, Object> params = new HashMap<>();
                params.put("id", coupon.getId());
                params.put("stock", 1);

                Integer updateRow = couponMapper.decStock(params);
                if (updateRow == 0) {
                    throw new CustomException("已经领完了");
                }

            }

    }


    //无取购提货券使用规则
    @Transactional(rollbackFor = Exception.class)
    public CouponCode createAndInc(Coupon coupon, Long memberId, String sn, Integer quantity) {

        if (!coupon.getType().equals(3)) {
            throw new CustomException("不是提货券");
        }

        if (coupon.getMaxgiven()!=null && coupon.getMaxgiven()>0) {
            throw new CustomException("有月限量,不能累加");
        }

        CouponCode couponCode = new CouponCode();

        Map<String,Object> params = new HashMap<>();
        params.put("couponId",coupon.getId());
        params.put("isUsed",false);
        params.put("memberId",memberId);
        List<CouponCode> voList = couponCodeMapper.selectList(params);
        if (voList.size()>0) {
            couponCode = voList.get(0);
        } else {
            couponCode.setBalance(0L);
            couponCode.setStock(0L);
            couponCode.setDeleted(false);
            couponCode.setCode(CodeGenerator.getUUID());
            couponCode.setCouponId(coupon.getId());
            couponCode.setEnterpriseId(coupon.getEnterpriseId());
            couponCode.setCreateDate(new Date());
            couponCode.setMemberId(memberId);
        }

        couponCode.setBalance(couponCode.getBalance()+new Long(quantity));
        couponCode.setIsUsed(false);
        couponCode.setStock(couponCode.getStock()+new Long(quantity));

        couponCode.setStartDate(coupon.getBeginDate());
        couponCode.setVaildDate(coupon.getEndDate());

        if (couponCode.getId()==null) {
            super.insertUseGeneratedKeys(couponCode);
        } else {
            super.updateByPrimaryKeySelective(couponCode);
        }


        return couponCode;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(Object[] ids) {
        int rw = 0;
        for (Object id:ids) {
            CouponCode couponCode = selectByPrimaryKey(id);
            couponCode.setDeleted(true);
            rw = rw + super.updateByPrimaryKeySelective(couponCode);
        }
        return rw;
    }


    public List<CouponCodeVo> getCouponCodeVoList(Long memberId) {
        Map<String,Object> params = new HashMap<>();
        params.put("memberId",memberId);
        return couponCodeMapper.selectVoList(params);
    }



    public List<CouponCodeVo> selectExchangeVoList(Long memberId,Long productId) {
        Map<String,Object> params = new HashMap<>();
        params.put("memberId",memberId);
        params.put("productId",productId);
        return couponCodeMapper.selectExchangeVoList(params);
    }


    public CouponCodeVo selectVoOne(Long id) {
        Map<String,Object> params = new HashMap<>();
        params.put("id",id);
        List<CouponCodeVo> voList = couponCodeMapper.selectVoOne(params);
        if (voList.size()>0) {
            return voList.get(0);
        } else {
            return null;
        }
    }

}
